package com.itheima.es_goods_demo.service.impl;

import com.alibaba.fastjson.JSON;
import com.itheima.es_goods_demo.mapper.GoodsMapper;
import com.itheima.es_goods_demo.pojo.Goods;
import com.itheima.es_goods_demo.service.GoodsService;
import com.itheima.es_goods_demo.utils.KibanaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

import java.util.List;

@Component
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    private GoodsMapper goodsMapper;

    @Override
    public Integer findAll() {
        return goodsMapper.findAll();
    }

    @Override
    public Goods findGoodsById(Long id) {
        if (KibanaUtil.isIndexExits("heima")) {
            try {
                Goods goods = JSON.parseObject(KibanaUtil.getDocument("heima", id.toString()),Goods.class);
                System.out.println(goods);
                return goods;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return goodsMapper.findGoodsById(id);
    }


    @Override
    public void export() {
        KibanaUtil.createIndexAndMapping("heima","{\n" +
                "  \"mappings\" : {\n" +
                "      \"properties\" : {\n" +
                "        \"name\" : {\n" +
                "          \"type\" : \"text\",\n" +
                "          \"analyzer\":\"ik_max_word\"\n" +
                "        },\n" +
                "        \"image\" : {\n" +
                "          \"type\" : \"keyword\",\n" +
                "          \"index\": false\n" +
                "        },\n" +
                "        \"updateTime\" : {\n" +
                "          \"type\" : \"date\"\n" +
                "        },\n" +
                "        \"categoryName\":{\n" +
                "          \"type\": \"keyword\"\n" +
                "        }\n" +
                "        \n" +
                "      }\n" +
                "    }\n" +
                "  \n" +
                "}");

        int times = findAll()/10000 +1;
        for (int i = 0; i < times; i++) {

            List<Goods> list  = findByPage(i,10000);
            System.out.println(list.size());
            for (Goods goods : list) {

                KibanaUtil.bulkAdd("heima",goods.getId().toString(), JSON.toJSONString(goods));
            }
            KibanaUtil.bulkExport();
        }
    }
    @Override
    public List<Goods> findByPage(int currentPage, int pageSize) {
        return goodsMapper.findByPage(currentPage * pageSize,pageSize);
    }
}
